import React, { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useAuthToken } from "../AuthTokenContext";
import { useAuth0 } from "@auth0/auth0-react";
import {
  Divider,
  Space,
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Table,
  Typography,
  Image,
  Tooltip,
  Tag,
  message,
} from "antd";
const originData = [];
const { Search } = Input;
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
          children
        )}
    </td>
  );
};
const MovieList = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [loading, setLoading] = useState(false);
  const [editingKey, setEditingKey] = useState("");
  const { accessToken } = useAuthToken();
  const navigate = useNavigate();
  const { isAuthenticated, isLoading } = useAuth0();
  const keywordRef = useRef("");
  // 设置分页参数
  const [tableParams, setTableParams] = useState({
    size: "small",
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const isEditing = (record) => record.id === editingKey;
  const edit = (record) => {
    form.setFieldsValue({
      title: "",
      description: "",
      ...record,
    });
    setEditingKey(record.id);
  };
  const fetchMovieList = async ({ current, pageSize }) => {
    setLoading(true);
    const url = `${process.env.REACT_APP_API_URL}/queryMoiveList?pageSize=${pageSize}&current=${current}&keyword=${keywordRef.current}`;
    const options = {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${accessToken}`,
      },
    };
    // lqt06170111W@
    try {
      const response = await fetch(url, options);
      const res = await response.json();
      const { result, total } = res;
      setLoading(false);
      setData(result);
      console.log(result);
      setTableParams({
        ...tableParams,
        pagination: {
          current,
          pageSize,
          total,
          // 200 is mock data, you should read it from server
          // total: data.totalCount,
        },
      });
    } catch (error) {
      console.error(error);
    }
  };
  useEffect(() => {
    if (isAuthenticated && accessToken) {
      const { current, pageSize } = tableParams.pagination;
      fetchMovieList({ current, pageSize });
    }
  }, [accessToken, isLoading]);
  const cancel = () => {
    setEditingKey("");
  };
  const saveRow = async ({ id, ratingId }) => {
    try {
      const row = await form.validateFields();
      const { title, description, rating } = row;
      const url = "http://localhost:8000/updateMovie"; // 替换为您的服务器地址
      const params = { id, ratingId, title, description, rating };

      const response = await fetch(url, {
        method: "POST", // 发送 POST 请求
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify(params), // 将 JavaScript 对象转换为 JSON 字符串
      });
      const { msg } = await response.json();
      message.success(msg);
      setEditingKey("");
      const { current, pageSize } = tableParams.pagination;
      fetchMovieList({ current, pageSize });
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
      setEditingKey("");
    }
  };
  const handleDelete = ({ id, ratingId }) => {
    // const url = 'http://localhost:8000/deleteMovie'; // 替换为您的服务器地址
    // const data = { movieId: id, ratingId };
    setData((prev) => prev.filter((r) => r.id != id));
    // fetch(url, {
    //   method: 'DELETE', // 使用 DELETE 方法
    //   headers: {
    //     'Content-Type': 'application/json',
    //     Authorization: `Bearer ${accessToken}`,
    //   },
    //   body: JSON.stringify(data) // 将 JavaScript 对象转换为 JSON 字符串
    // })
    //   .then(response => {
    //     return response.json(); // 或者 response.json()，如果您的服务器返回 JSON
    //   })
    //   .then(data => {
    //     message.success(data?.msg);
    //     const { current, pageSize } = tableParams.pagination;
    //     fetchMovieList({ current, pageSize })
    //   })
    //   .catch(error => {
    //     console.error('Error deleting movie:', error);
    //   });
  };
  const columns = [
    {
      title: "title",
      dataIndex: "title",
      width: "15%",
      editable: true,
      render: (text, row) => (
        <a
          onClick={(e) => {
            e.preventDefault();
            navigate(`/app/movieDetail/${row.id}`, { state: row });
          }}
        >
          {text}
        </a>
      ),
    },
    {
      title: "image",
      dataIndex: "image",
      width: "10%",
      responsive: ["md"],
      render: (uri) => <Image width={42} height={50} src={uri} />,
    },
    {
      title: "description",
      dataIndex: "description",
      width: "40%",
      responsive: ["md"],
      editable: true,
      ellipsis: {
        showTitle: false,
      },
      render: (description) => (
        <Tooltip placement="topLeft" title={description}>
          {description}
        </Tooltip>
      ),
    },
    {
      title: "rating",
      dataIndex: "rating",
      width: "10%",
      editable: true,
      responsive: ["md"],
    },
    {
      title: "genre",
      dataIndex: "genre",
      width: "10%",
      responsive: ["md"],
      render: (_, { genre }) => (
        <>
          {genre.map((tag) => {
            let color = genre.length > 2 ? "green" : "cyan";
            return (
              <Tag color={color} key={tag} bordered={false}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "operation",
      dataIndex: "operation",
      responsive: ["md"],
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => saveRow(record)}
              style={{
                marginRight: 8,
              }}
            >
              Save
            </Typography.Link>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
            <Space>
              <Typography.Link
                disabled={editingKey !== ""}
                onClick={() => edit(record)}
              >
                Edit
            </Typography.Link>
              <Divider type="vertical" />
              <Popconfirm
                title="Sure to delete?"
                onConfirm={() => handleDelete(record)}
              >
                <a>Delete</a>
              </Popconfirm>
            </Space>
          );
      },
    },
  ];
  const handlePagenationChange = (current, pageSize) => {
    setTableParams({
      ...tableParams,
      pagination: {
        ...tableParams.pagination,
        current,
        pageSize,
      },
    });
    cancel();
    fetchMovieList({ current, pageSize });
  };
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "rating" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  const onSearch = (value) => {
    keywordRef.current = value;
    const { current, pageSize } = tableParams.pagination;
    fetchMovieList({ current, pageSize });
  };
  return (
    <div>
      <Search placeholder="Enter the name or gene" allowClear style={{ width: '40%' }} onSearch={onSearch} enterButton />
      <Form form={form} component={false}>
        <Table
          style={{ height: "750px" }}
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          loading={loading}
          bordered
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          size="small"
          pagination={{
            ...tableParams.pagination,
            onChange: handlePagenationChange,
          }}
        />
      </Form>
    </div>
  );
};
export default MovieList;
